package com.webchat.rmi.filter;

import com.webchat.common.constants.RpcRequestConstants;
import com.webchat.common.enums.BaseErrCodeEnum;
import com.webchat.common.util.JsonUtil;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RpcRequestPermissionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String ak = request.getHeader(RpcRequestConstants.RPC_REQUEST_ACCESS_KEY);
        String sk = request.getHeader(RpcRequestConstants.RPC_REQUEST_SECRET_KEY);

        if (this.doCheck(ak, sk)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        this.noRequestPermission(response);
        log.error("RPC内部调用鉴权失败。request_url:{}, ak:{}, sk:{}", request.getRequestURL(), ak, sk);
    }


    private boolean doCheck(String ak, String sk) {

        return true;
//        return RpcRequestConstants.RPC_REQUEST_DEFAULT_AK.equals(ak) &&
//               RpcRequestConstants.RPC_REQUEST_DEFAULT_SK.equals(sk);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }


    private void noRequestPermission(HttpServletResponse response) {
        Map<String, Object> responseMap = new HashMap<>();
        response.setCharacterEncoding("UTF-8"); // 设置字符编码为 UTF-8
        response.setContentType("application/json;charset=UTF-8"); // 设置内容类型和字符编码
        responseMap.put("code", BaseErrCodeEnum.RPC_REQUEST_UN_PERMISSION.getCode());
        responseMap.put("message", BaseErrCodeEnum.RPC_REQUEST_UN_PERMISSION.getMessage());
        try {
            response.getWriter().println(JsonUtil.toJsonString(responseMap));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
